

import glUtils from "../utils/glUtils";

/**
 * desc:
 * 顶点和颜色分别用一个buffer
 */

const vs = `#version 300 es

layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec4 vColor;

out vec4 color;
void main() {
    gl_Position = vPosition;
    color = vColor;
}
`;

const fs = `#version 300 es
precision mediump float;

in vec4 color;
out vec4 fColor;

void main() {
    fColor = color;
}
`;

export default  {

    gl:null,
    bInited:false,

    // handle
    vPosition:0,
    vColor:1,

    init(gl){
        this.gl = gl;

        this.vao = gl.createVertexArray();
        gl.bindVertexArray(this.vao);

        let vertices = [
            0,0.5,
            -0.5,-0.5,
            0.5,-0.5
        ];
        let colors = [
            1,0,0,1,
            0,1,0,1,
            0,0,1,1
        ];

        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(this.vPosition);
        gl.vertexAttribPointer(this.vPosition,2,gl.FLOAT,false,0,0);

        this.cbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,this.cbo);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(colors),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(this.vColor);
        gl.vertexAttribPointer(this.vColor,4,gl.FLOAT,false,0,0);

        gl.bindVertexArray(null);

        this.program = glUtils.createProgram(gl,vs,fs);

        this.bInited = true;
    },

    render(){
        if(!this.bInited){
            return;
        }

        let gl = this.gl;

        gl.useProgram(this.program);
        gl.bindVertexArray(this.vao);
        gl.drawArrays(gl.TRIANGLES,0,3);
        gl.bindVertexArray(null);
    },
}